package com.origin.utils.activity

import android.Manifest
import android.content.Intent
import android.database.Cursor
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.provider.ContactsContract
import android.util.Log
import com.origin.utils.R
import com.origin.utils.ToastUtils
import com.origin.utils.log.LogUtils
import com.origin.utils.permissions.OnActivityResultCallback
import com.origin.utils.permissions.OnPermissionPageCallback
import com.origin.utils.permissions.PermissionsUtils
import kotlinx.android.synthetic.main.activity_permissions_request.*

class PermissionsRequestActivity : AppCompatActivity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_permissions_request)
        requestPermissionsBn.setOnClickListener {
            PermissionsUtils.simpleRequestPermissions(this, Manifest.permission.READ_CONTACTS, onPermissionPageCallback = object : OnPermissionPageCallback {
                override fun onGranted(permissions: MutableList<String>) {
                    Log.e("PermissionsRequest", "onGranted ${permissions}")
                    fetchContacts()
                }

                override fun onDenied(permissions: MutableList<String>) {
                    Log.e("PermissionsRequest", "onDenied ${permissions}")
                }

            });
        }
        forResultBn.setOnClickListener {
            val intent = Intent(this, TeActivity::class.java)
            intent.putExtra("name", "Yang")
            PermissionsUtils.startActivityForResult(this, intent, { requestCode, resultCode, data ->
                data?.apply {
                    Log.e("onActivityResult", "requestCode ${requestCode}  resultCode ${resultCode} name_after ${this.getStringExtra("name_after")} ");
                }
            }, 300)
        }
    }

    private fun fetchContacts() {
        // 定义要查询的列
        val projection = arrayOf(
            ContactsContract.Contacts._ID,
            ContactsContract.Contacts.DISPLAY_NAME
        )

        // 执行查询
        val cursor: Cursor? = contentResolver.query(
            ContactsContract.Contacts.CONTENT_URI,
            projection,
            null,
            null,
            null
        )
        LogUtils.__e("获取到了通讯录x")
        cursor?.use {
            if (it.count > 0) {
                LogUtils.__e("获取到了通讯录")
            }else{
                LogUtils.__e("获取到了通讯录长度为0")
            }
        }
    }
}